﻿// HelloLua.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string.h>
#include <iostream>
using namespace std;
#pragma comment (lib,"Lua.lib")
#include "lua.hpp"


void luacallc()
{

}

lua_State* L;
static int  average(lua_State* L)
{
	int n = lua_gettop(L); //得到参数个数
	double sum = 0;
	int i = -1*n;
	for (i; i <= -1; i++)
	{
		sum += lua_tonumber(L, i);//依次出栈
	}
	lua_pushnumber(L, sum / n); //压入平均值
	lua_pushnumber(L, sum); //压入总和
	return 2;
}


int _tmain(int argc, _TCHAR* argv[])
{
	lua_State* lua_state = luaL_newstate(); //返回一个指向堆栈的指针
	luaL_openlibs(lua_state); //加载一些lua必须的库类似Print
	//luaL_dofile(lua_state, "hello.lua");
	//lua_close(lua_state);
	//getchar();
	if (lua_state == NULL)
	{
		return 0;
	}

	//////////////////////////////////////////////////////////////////////////
	lua_register(lua_state, "average", average);

	luaL_dofile(lua_state, "helloc.lua");
	//////////////////////////////////////////////////////////////////////////

	/*
	int bRet = luaL_loadfile(lua_state, "hello.lua"); //编译lua文件
	if (bRet)
	{
		cout << "load file error" << endl;
	}

	bRet = lua_pcall(lua_state, 0, 0, 0); //实例化lua文件
	if (bRet)
	{
		cout << "pcall error" << endl;
		const char *pErrorMsg = lua_tostring(lua_state, -1);
		cout << pErrorMsg << endl;
	}

	lua_getglobal(lua_state, "str"); //把全局的值压到栈顶
	string str = lua_tostring(lua_state, -1);
	cout << "str=" << str.c_str() << endl;

	int top = lua_gettop(lua_state);
	cout << "lua state top   " << top << endl;

	lua_getglobal(lua_state, "tb1");
	//void lua_getfield (lua_State *L, int index, const char *k);
	lua_getfield(lua_state, -1, "name"); //将t[k]压入堆栈
	str = lua_tostring(lua_state, -1);

	lua_getfield(lua_state, -2, "id"); //  tb1 = {name = "shun", id=2018}   name -1 , id -2
	int index = lua_tointeger(lua_state, -1);

	cout << "tb1:id = " << index << endl;
	cout << "tb1:name = " << str.c_str() << endl;

	top = lua_gettop(lua_state);
	cout << "lua state top   " << top << endl;

	lua_getglobal(lua_state, "add"); //获取函数，压入栈中
	lua_pushnumber(lua_state, 10); //压入第一个参数
	lua_pushnumber(lua_state, 20); //压入第二个参数
	int iRet = lua_pcall(lua_state, 2, 1, 0); //将参数出栈，函数出栈，压入函数结果

	if (iRet)
	{
		const char *pErrorMsg = lua_tostring(lua_state, -1);
		cout << pErrorMsg << endl;
		lua_close(lua_state);
		return 0;
	}

	if (lua_isnumber(lua_state, -1))
	{
		double fValue = lua_tonumber(lua_state, -1);
		cout << "Result is   " << fValue << endl;
	}

	top = lua_gettop(lua_state);
	cout << "lua state top   " << top << endl;

	//至此，栈中的情况是：  
	//=================== 栈顶 ===================   
	//  索引  类型      值  
	//   4   int：      30   
	//   3   string：   shun   
	//   2   table:     tbl  
	//   1   string:    I am so cool~  
	//=================== 栈底 ===================   

	*/
	//7.关闭state  
	lua_close(lua_state);

	int tempin;
	cin >> tempin;

	return 0;
}

